package com.eastfair.security.apiconditioncore;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * 自定义request请求拦截处理器
 * ligang
 * 2020/03/27
 */
public class RequestMappingHandlerMappingCore extends RequestMappingHandlerMapping {
    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return createCondition(apiVersion);
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        if(apiVersion!=null){
            //方法上的url值
            String methodUrl = null;
            if(method.getAnnotation(PostMapping.class)!=null){
                methodUrl = method.getAnnotation(PostMapping.class).value()[0];
            }else if(method.getAnnotation(GetMapping.class)!=null){
                methodUrl = method.getAnnotation(GetMapping.class).value()[0];
            }else if(method.getAnnotation(PutMapping.class)!=null){
                methodUrl = method.getAnnotation(PutMapping.class).value()[0];
            }else if(method.getAnnotation(DeleteMapping.class)!=null){
                methodUrl = method.getAnnotation(DeleteMapping.class).value()[0];
            }
            String methodUrlPath= method.getDeclaringClass().getAnnotation(RequestMapping.class).value()[0]+methodUrl;
            ConditionData.setApiVersion(methodUrlPath, ConditionUtil.parseVersion(apiVersion.value()));
            return createCondition(apiVersion);
        }
        return null;
    }

    private RequestCondition<ApiVersionRequestCondition> createCondition(ApiVersion apiVersion) {
        if(apiVersion!=null){
            return apiVersion == null ? null : new ApiVersionRequestCondition(ConditionUtil.parseVersion(apiVersion.value()));
        }
       return null;
    }


}
